﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mime;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using WkHtmlToXSharp;

namespace DentScan2.WebApp
{
    public partial class Calc : Classes.BaseForm
    {

        public String UID
        {
            get
            {
                return ViewState["UID"].ToString();

            }
            set
            {
                ViewState["UID"] = value;
            }
        }

        public string DetailKindId
        {
            get
            {
                return ViewState["DetailKindId"] == null ? null : ViewState["DetailKindId"].ToString();
            }
            set
            {
                ViewState["DetailKindId"] = value;
            }
        }

        public long Obs
        {
            get
            {
                long result = 0;
                for (int i = 0; i < cblObs.Items.Count; i++)
                    if (cblObs.Items[i].Selected)
                        result += (long)Math.Pow(2, (double)i);
                return result;
            }

            set
            {
                for (int i = 0; i < cblObs.Items.Count; i++)
                    cblObs.Items[i].Selected = ((value & (long)Math.Pow(2, (double)i)) > 0);
            }
        }




        protected void Page_Load(object sender, EventArgs e)
        {
            this.CheckLogged();

            if (!IsPostBack)
            {
                InitDDLs();
                SetData();
                ReCalc();
                DisplayFormLink();
                ColorDetails();
                ShowJustMinutes();
                ltMethodName.Text = this.Damage.CalcData.MethodName;
            }


        }

        public bool JustHoursSelected()
        {
            return Damage.JustHours;
        }

        private void InitDDLs()
        {
            for (int i = 0; i <= 100; i++)
                ddlDiscountPercent.Items.Add(new ListItem() { Text = i.ToString(), Value = i.ToString() });
            for (int i = 0; i <= 500; i += 10)
                ddlDissasemblyTimeDetail.Items.Add(new ListItem() { Text = i.ToString(), Value = i.ToString() });
            for (int i = 0; i <= 200; i++)
                ddlAdditionalMaterialsTotal.Items.Add(new ListItem() { Text = i.ToString(), Value = i.ToString() });
            for (int i = 0; i <= 500; i += 10)
                ddlDissasemblyTime.Items.Add(new ListItem() { Text = i.ToString(), Value = i.ToString() });
            for (int i = 0; i <= 500; i += 10)
                ddlDisassemblyPrice.Items.Add(new ListItem() { Text = i.ToString(), Value = i.ToString() });
            for (int i = 0; i <= 500; i += 10)
                ddlDisassemblyPriceDetail.Items.Add(new ListItem() { Text = i.ToString(), Value = i.ToString() });
            for (int i = 0; i <= 500; i += 10)
                ddlPreparationTime.Items.Add(new ListItem() { Text = i.ToString(), Value = i.ToString() });
            for (int i = 0; i <= 200; i++)
                ddlAdditionalMaterials.Items.Add(new ListItem() { Text = i.ToString(), Value = i.ToString() });

            ddlDissasemblyTime.Visible = this.Damage.JustHours;
            ddlDisassemblyPrice.Visible = !ddlDissasemblyTime.Visible;
            ddlDissasemblyTimeDetail.Visible = this.Damage.JustHours;
            ddlDisassemblyPriceDetail.Visible = !ddlDissasemblyTime.Visible;
            lTotalDissasemblyTime.Visible = this.Damage.JustHours;

        }

        private void DisplayFormLink()
        {
            if (this.Damage.DamageIdentifier.HasValue)
            {
                UID = Guid.NewGuid().ToString();
                Cache.Add(UID, this.Damage.DamageId.ToString(), null, DateTime.Now.AddHours(10), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
                pShowWhenSaved.Visible = true;
                hlForm.NavigateUrl = string.Format("form.aspx?uid={0}&areaId={1}", UID, this.AreaId.ToString());
            }
            else
                pShowWhenSaved.Visible = false;
        }

        private void InitSingleSizeDdl(DropDownList ddl, int max)
        {
            ddl.Items.Clear();
            for (int i = 0; i <= max; i++)
                ddl.Items.Add(new ListItem() { Text = i.ToString(), Value = i.ToString() });
        }

        private void InitSizeDDLS(string detailKindId)
        {
            bool isHorizontal = dl.DetailKinds.First(dk => dk.DetailKindId == this.DetailKindId).IsHorizontal;
            int max1 = (from aw in this.Damage.CalcData.AWS
                        where aw.SizeTo == 1 && aw.IsHorizontal == isHorizontal
                        select aw.Cnt).Max();
            int max2 = (from aw in this.Damage.CalcData.AWS
                        where aw.SizeTo == 2 && aw.IsHorizontal == isHorizontal
                        select aw.Cnt).Max();
            int max3 = (from aw in this.Damage.CalcData.AWS
                        where aw.SizeTo == 3 && aw.IsHorizontal == isHorizontal
                        select aw.Cnt).Max();
            int max4 = (from aw in this.Damage.CalcData.AWS
                        where aw.SizeTo == 4 && aw.IsHorizontal == isHorizontal
                        select aw.Cnt).Max();
            InitSingleSizeDdl(ddlSize1, max1);
            InitSingleSizeDdl(ddlSize2, max2);
            InitSingleSizeDdl(ddlSize3, max3);
            InitSingleSizeDdl(ddlSize4, max4);
        }

        private void Edit()
        {
            lDetailName.Text = Tools.Tools.GetDetailNameById(DetailKindId);
            imgDetail.ImageUrl = "~/Img/car/" + DetailKindId + ".png";
            var detail = Damage.DamageDetails.Where(d => d.DetailKindId == this.DetailKindId).FirstOrDefault();
            InitSizeDDLS(this.DetailKindId);
            if (detail == null)
            {
                ddlSize1.SelectedValue = "0";
                ddlSize2.SelectedValue = "0";
                ddlSize3.SelectedValue = "0";
                ddlSize4.SelectedValue = "0";
                ddlDissasemblyTimeDetail.SelectedValue = "0";
                ddlAdditionalMaterials.SelectedValue = "0";
                tbMinutes.Text = "0";
                cbPNP.Checked = false;
                cbALU.Checked = false;
                cbPolish.Checked = false;
                cbTraditional.Checked = false;
                cbWithReserve.Checked = false;
                Obs = 0;
            }
            else
            {
                ddlSize1.SelectedValue = detail.Size1.ToString();
                ddlSize2.SelectedValue = detail.Size2.ToString();
                ddlSize3.SelectedValue = detail.Size3.ToString();
                ddlSize4.SelectedValue = detail.Size4.ToString();
                tbMinutes.Text = detail.Minutes.ToString();
                //cbJustHours.Checked = detail.JustHours;
                ddlDissasemblyTimeDetail.SelectedValue = detail.DisassemblyTime.ToString();
                ddlDisassemblyPriceDetail.SelectedValue = detail.DisassemblyPrice.ToString();
                ddlAdditionalMaterials.SelectedValue = ((int)detail.Materials).ToString();
                cbPNP.Checked = detail.PNP;
                cbALU.Checked = detail.ALU;
                cbPolish.Checked = detail.Polish;
                cbTraditional.Checked = detail.Traditional;
                Obs = detail.Obs;
                cbWithReserve.Checked = detail.WithReserve;

            }
            // проверява cbJustHours
            ShowJustMinutes();

            mvCalc.SetActiveView(vElement);
            GetDetailPrice();
        }

        private void SaveDetail()
        {
            Classes.DamageDetail detail = Damage.DamageDetails.Where(d => d.DetailKindId == this.DetailKindId).FirstOrDefault();
            if (detail == null)
            {
                detail = new Classes.DamageDetail()
                {
                    DetailKindId = this.DetailKindId,
                    Size1 = int.Parse(ddlSize1.SelectedValue),
                    Size2 = int.Parse(ddlSize2.SelectedValue),
                    Size3 = int.Parse(ddlSize3.SelectedValue),
                    Size4 = int.Parse(ddlSize4.SelectedValue),
                    Minutes = int.Parse(tbMinutes.Text == "" ? "0" : tbMinutes.Text),
                    //JustHours = cbJustHours.Checked,
                    DisassemblyTime = int.Parse(ddlDissasemblyTimeDetail.SelectedValue == "" ? "0" : ddlDissasemblyTimeDetail.SelectedValue),
                    DisassemblyPrice = int.Parse(ddlDisassemblyPriceDetail.SelectedValue == "" ? "0" : ddlDisassemblyPriceDetail.SelectedValue),
                    Materials = decimal.Parse(ddlAdditionalMaterials.SelectedValue),
                    PNP = cbPNP.Checked,
                    ALU = cbALU.Checked,
                    Polish = cbPolish.Checked,
                    Traditional = cbTraditional.Checked,
                    WithReserve = cbWithReserve.Checked
                };
                Damage.DamageDetails.Add(detail);
            }
            else
            {
                detail = Damage.DamageDetails.Where(d => d.DetailKindId == this.DetailKindId).FirstOrDefault();
                detail.Size1 = int.Parse(ddlSize1.SelectedValue);
                detail.Size2 = int.Parse(ddlSize2.SelectedValue);
                detail.Size3 = int.Parse(ddlSize3.SelectedValue);
                detail.Size4 = int.Parse(ddlSize4.SelectedValue);
                //detail.JustHours = cbJustHours.Checked;
                detail.Minutes = int.Parse(tbMinutes.Text == "" ? "0" : tbMinutes.Text);
                detail.DisassemblyTime = int.Parse(ddlDissasemblyTimeDetail.SelectedValue == "" ? "0" : ddlDissasemblyTimeDetail.SelectedValue);
                detail.DisassemblyPrice = int.Parse(ddlDisassemblyPriceDetail.SelectedValue == "" ? "0" : ddlDisassemblyPriceDetail.SelectedValue);
                detail.Materials = decimal.Parse(ddlAdditionalMaterials.SelectedValue);
                detail.PNP = cbPNP.Checked;
                detail.ALU = cbALU.Checked;
                detail.Polish = cbPolish.Checked;
                detail.Traditional = cbTraditional.Checked;
                detail.WithReserve = cbWithReserve.Checked;
            }

            int allAw = 0;
            bool isHorizontal = dl.DetailKinds.First(dk => dk.DetailKindId == this.DetailKindId).IsHorizontal;

            if (detail.Size1 > 0)
                allAw += this.Damage.CalcData.AWS.First(aw => aw.SizeTo == 1 && aw.IsHorizontal == isHorizontal && aw.Cnt == detail.Size1).AW;
            if (detail.Size2 > 0)
                allAw += this.Damage.CalcData.AWS.First(aw => aw.SizeTo == 2 && aw.IsHorizontal == isHorizontal && aw.Cnt == detail.Size2).AW;
            if (detail.Size3 > 0)
                allAw += this.Damage.CalcData.AWS.First(aw => aw.SizeTo == 3 && aw.IsHorizontal == isHorizontal && aw.Cnt == detail.Size3).AW;
            if (detail.Size4 > 0)
                allAw += this.Damage.CalcData.AWS.First(aw => aw.SizeTo == 4 && aw.IsHorizontal == isHorizontal && aw.Cnt == detail.Size4).AW;

            detail.AWS = allAw;
            detail.Obs = this.Obs;
            detail.ObsStr = this.GetObsString(detail.Obs);
            RecalcDetail(detail);
            ReCalc();
            mvCalc.SetActiveView(vTable);
        }


        private void RecalcDetail(Classes.DamageDetail detail)
        {

            decimal awsHours = detail.AWS / (decimal)this.Damage.CalcData.AreaCalcData.AWToHour;
            if (this.Damage.JustHours)
                awsHours = (decimal)detail.Minutes / (decimal)60;
            decimal awsPrice = awsHours * this.Damage.CalcData.AreaCalcData.HourPrice;

            decimal aluPrice = cbALU.Checked ? (decimal)this.Damage.CalcData.AreaCalcData.Alum * awsPrice / 100 : 0;
            decimal polishPrice = cbPolish.Checked ? (decimal)this.Damage.CalcData.AreaCalcData.PolishPercent * awsPrice / 100 : 0;
            decimal pnpPrice = cbPNP.Checked ? (decimal)this.Damage.CalcData.AreaCalcData.PNPPercent * awsPrice / 100 : 0;

            awsPrice += aluPrice;
            awsPrice += polishPrice;
            awsPrice -= pnpPrice;
            decimal dissasemblyPrice = this.Damage.CalcData.AreaCalcData.DisassemblyHourPrice * (decimal)detail.DisassemblyTime / (decimal)60 +
                (decimal)(detail.DisassemblyPrice);

            detail.Price = awsPrice + dissasemblyPrice;
            detail.Price += detail.Materials;
            if (detail.Traditional)
                detail.Price = 0;
        }

        private void ReCalc()
        {

            decimal totalPrice = Damage.DamageDetails.Sum(dd => dd.Price);
            //decimal time = totalAws / (decimal)area.AWToHour + decimal.Parse(tbPrepTime.Text) / (decimal)60;
            //decimal price = time * (decimal)area.HourPrice;
            decimal dissasemblyPrice = this.Damage.CalcData.AreaCalcData.DisassemblyHourPrice * decimal.Parse(ddlDissasemblyTime.SelectedValue) / (decimal)60;
            decimal preparationPrice = this.Damage.CalcData.AreaCalcData.PreparationHourPrice * decimal.Parse(ddlPreparationTime.SelectedValue) / (decimal)60;
            totalPrice = totalPrice + dissasemblyPrice;
            totalPrice = totalPrice + preparationPrice;
            totalPrice = totalPrice + int.Parse(ddlAdditionalMaterialsTotal.SelectedValue) + int.Parse(ddlDisassemblyPrice.SelectedValue);
            decimal priceWithDiscount = totalPrice * ((decimal)100 - (Damage.Discount.HasValue ? Damage.Discount.Value : 0)) / (decimal)100;
            decimal discount = Damage.Discount.HasValue ? Damage.Discount.Value : 0;
            decimal discountPrice = totalPrice > 0 ? discount * totalPrice / 100M : 0M;
            decimal vat = priceWithDiscount * (decimal)this.Damage.CalcData.AreaCalcData.VAT / (decimal)100;
            int totalDissasemblyTime = Damage.DamageDetails.Sum(dd => dd.DisassemblyTime) + int.Parse(ddlDissasemblyTime.SelectedValue);
            int totalDissasemblyPrice2 = Damage.DamageDetails.Sum(dd => dd.DisassemblyPrice) + int.Parse(ddlDisassemblyPrice.SelectedValue);
            decimal totalDissasemblyPrice = (decimal)totalDissasemblyTime * this.Damage.CalcData.AreaCalcData.DisassemblyHourPrice / (decimal)60 +
                (decimal)(totalDissasemblyPrice2);
            lTotalDissasemblyTime.Text = totalDissasemblyTime.ToString();
            lTotalDissasemblyTimeSum.Text = totalDissasemblyPrice.ToString("0.00");
            lAdditionalMaterialsWithDetails.Text = (int.Parse(ddlAdditionalMaterialsTotal.SelectedValue) + (int)Damage.DamageDetails.Sum(dd => dd.Materials)).ToString();
            lPreparationPrice.Text = preparationPrice.ToString("0.00");
            decimal priceWithVat = priceWithDiscount + vat;
            Damage.VAT = this.Damage.CalcData.AreaCalcData.VAT;
            Damage.Discount = discount;
            Damage.Total = priceWithDiscount;

            lPriceNoVatNoDIscount.Text = totalPrice.ToString("0.00");
            lPriceNoVatDIscount.Text = priceWithDiscount.ToString("0.00");
            lDiscountPercent.Text = discount.ToString("0.00");
            lDiscountPrice.Text = discountPrice.ToString("0.00");
            lVat.Text = vat.ToString("0.00");
            lTotal.Text = priceWithVat.ToString("0.00");
            rDamageDetails.DataSource = this.Damage.DamageDetails;
            rDamageDetails.DataBind();

        }


        private void EditSettings(int mode)
        {

            if (mode == 2)
            {
                mvCalc.SetActiveView(vSettings);
                if (tbDiscount.Text == "")
                    tbDiscount.Text = "0";
            }
            else
            {
                mvCalc.SetActiveView(vSettings2);
            }
        }

        private void SaveSettings()
        {
            decimal newSum = tbDiscount.Text == "" ? 0 : decimal.Parse(tbDiscount.Text);
            Damage.Discount = (decimal.Parse(lPriceNoVatNoDIscount.Text) - newSum) * 100 / decimal.Parse(lPriceNoVatNoDIscount.Text);
            ReCalc();
            mvCalc.SetActiveView(vTable);

        }

        private void SaveSettings2()
        {
            Damage.Discount = tbDiscount.Text == "" ? 0 : decimal.Parse(ddlDiscountPercent.SelectedValue);
            ReCalc();
            mvCalc.SetActiveView(vTable);
        }



        protected void bZLK_Click(object sender, EventArgs e)
        {
            DetailKindId = "ZLK";
            Edit();
        }

        protected void bZLV_Click(object sender, EventArgs e)
        {
            DetailKindId = "ZLV";
            Edit();
        }

        protected void bPLV_Click(object sender, EventArgs e)
        {
            DetailKindId = "PLV";
            Edit();
        }

        protected void bPLK_Click(object sender, EventArgs e)
        {
            DetailKindId = "PLK";
            Edit();
        }

        protected void bLK_Click(object sender, EventArgs e)
        {
            DetailKindId = "LK";
            Edit();
        }

        protected void bB_Click(object sender, EventArgs e)
        {
            DetailKindId = "B";
            Edit();
        }

        protected void bKAS_Click(object sender, EventArgs e)
        {
            DetailKindId = "KAS";
            Edit();
        }

        protected void bT_Click(object sender, EventArgs e)
        {
            DetailKindId = "T";
            Edit();
        }

        protected void bK_Click(object sender, EventArgs e)
        {
            DetailKindId = "K";
            Edit();
        }

        protected void bDK_Click(object sender, EventArgs e)
        {
            DetailKindId = "DK";
            Edit();
        }

        protected void bZDK_Click(object sender, EventArgs e)
        {
            DetailKindId = "ZDK";
            Edit();
        }

        protected void bZDV_Click(object sender, EventArgs e)
        {
            DetailKindId = "ZDV";
            Edit();
        }

        protected void bPDV_Click(object sender, EventArgs e)
        {
            DetailKindId = "PDV";
            Edit();
        }

        protected void bPDK_Click(object sender, EventArgs e)
        {
            DetailKindId = "PDK";
            Edit();
        }



        protected void bSaveDetail_Click(object sender, EventArgs e)
        {
            SaveDetail();
            ColorDetails();
            mvCalc.SetActiveView(vTable);
        }

        protected void bCancelDetail_Click(object sender, EventArgs e)
        {
            mvCalc.SetActiveView(vTable);
        }

        protected void bSaveDiscount_Click(object sender, EventArgs e)
        {
            SaveSettings();
            mvCalc.SetActiveView(vTable);
        }

        protected void bCancelDiscount_Click(object sender, EventArgs e)
        {
            mvCalc.SetActiveView(vTable);
        }

        private void SetData()
        {
            tbTechName.Text = Damage.TechName;
            tbTechPhone.Text = Damage.TechPhone;
            tbExpertiseDate.Text = Damage.ExpertiseDateStr == "" ? DateTime.Now.ToShortDateString() : Damage.ExpertiseDateStr;
            tbRepairDate.Text = Damage.RepairDateStr == "" ? "" : Damage.RepairDateStr;
            if (Damage.ExpertisePlaceId != null)
            {
                ucExpertisePlace.CountryId = Damage.ExpertiseCountryId;
                ucExpertisePlace.DistrictId = Damage.ExpertiseDistrictId;
                ucExpertisePlace.CityId = Damage.ExpertisePlaceId;
            }
            else
            {
                ucExpertisePlace.CountryId = Damage.Car.Owner.CountryId;
                ucExpertisePlace.DistrictId = Damage.Car.Owner.DistrictId;
                ucExpertisePlace.CityId = Damage.Car.Owner.CityId;
            }
            lDamageIdentifier.Text = Damage.DamageIdentifier.HasValue ? Damage.DamageIdentifier.Value.ToString() : "";
            foreach (var detail in Damage.DamageDetails)
                detail.ObsStr = this.GetObsString(detail.Obs);
            Damage.VAT = dl.Areas.Where(a => a.AreaId == this.AreaId).First().VAT.Value;
            cbExpertChecked.Checked = Damage.ExpertChecked;
            ddlAdditionalMaterialsTotal.SelectedValue = Damage.AdditionalMaterialsTotal.ToString();
            ddlDissasemblyTime.SelectedValue = Damage.DisassemblyTime.ToString();
            ddlDiscountPercent.SelectedValue = Damage.DisassemblyPrice.ToString();
            ddlPreparationTime.SelectedValue = Damage.PreparationTime.ToString();
        }

        private void GetData()
        {
            Damage.TechName = tbTechName.Text.ToUpper();
            Damage.TechPhone = tbTechPhone.Text.ToUpper();
            Damage.ExpertiseDate = DateTime.Parse(tbExpertiseDate.Text);
            if (tbRepairDate.Text != "")
                Damage.RepairDate = DateTime.Parse(tbRepairDate.Text);
            else
                Damage.RepairDate = null;
            Damage.ExpertisePlaceId = ucExpertisePlace.CityId;
            Damage.ExpertChecked = cbExpertChecked.Checked;
            Damage.AdditionalMaterialsTotal = int.Parse(ddlAdditionalMaterialsTotal.SelectedValue);
            Damage.PreparationTime = int.Parse(ddlPreparationTime.SelectedValue);
            Damage.DisassemblyTime = int.Parse(ddlDissasemblyTime.SelectedValue);
            Damage.DisassemblyPrice = int.Parse(ddlDisassemblyPrice.SelectedValue);
        }

        private string GetObsString(long obs)
        {
            List<string> lObs = new List<string>();
            for (int i = 0; i < cblObs.Items.Count; i++)
                if ((obs & (long)Math.Pow(2, (double)i)) > 0)
                    lObs.Add(cblObs.Items[i].Value);

            return string.Join(" ", lObs.ToArray());
        }

        protected void bSaveToDB_Click(object sender, EventArgs e)
        {
            Page.Validate("vg");
            if (!Page.IsValid)
                return;
            GetData();

            //Създаване на архив
            if (Damage.DamageId.HasValue)
            {
                Classes.Damage dArhive = new Classes.Damage(dl.Damages.First(d => d.DamageId == Damage.DamageId));
                dl.DamageArhives.InsertOnSubmit(new DB.DamageArhive()
                {
                    DamageArhiveId = Guid.NewGuid(),
                    DamageId = Damage.DamageId.Value,
                    ArhiveDate = DateTime.Now,
                    IsDel = false,
                    LastEditDate = DateTime.Now,
                    DamageXml = dArhive.GetXml()

                }

                    );
                dl.SubmitChanges();
            }
            //край на архив


            Damage.SaveToDB(dl, this.UserId.Value);
            if (!hlForm.Visible)
                DisplayFormLink();
            lDamageIdentifier.Text = Damage.DamageIdentifier.HasValue ? Damage.DamageIdentifier.Value.ToString() : "";

            lStatus.Text = "Щетата е записана";
        }

        protected void bPrev_Click(object sender, EventArgs e)
        {
            Response.Redirect("default.aspx", true);
        }

        protected void bSend_Click(object sender, EventArgs e)
        {
            if (tbToEmail1.Text != "" || tbToEmail2.Text != "" || tbToEmail3.Text != "")
            {
                try
                {
                    System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();
                    if (tbToEmail1.Text != "")
                        mm.To.Add(new System.Net.Mail.MailAddress(tbToEmail1.Text));
                    if (tbToEmail2.Text != "")
                        mm.To.Add(new System.Net.Mail.MailAddress(tbToEmail2.Text));
                    if (tbToEmail3.Text != "")
                        mm.To.Add(new System.Net.Mail.MailAddress(tbToEmail3.Text));
                    mm.Subject = "Expertise";
                    mm.Body = "";
                    mm.BodyEncoding = System.Text.Encoding.UTF8;
                    string protocol = Request.Url.Scheme;
                    string port = Request.Url.Port.ToString();
                    string server = Request.Url.Host;
                    string path = "";
                    for (int i = 0; i < Request.Url.Segments.Length - 1; i++)
                    {
                        var segment = Request.Url.Segments[i];
                        path += "/" + segment;
                    }
                    string url = protocol + "://" + server + ":" + port + path + string.Format("form.aspx?uid={0}&areaId={1}", UID, this.AreaId.ToString());


                    var attachment = new WebClient().DownloadData(url);
                    MemoryStream ms = new MemoryStream(attachment);
                    ms.Seek(0, SeekOrigin.Begin);
                    System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(ms, "expertise.pdf");
                    mm.Attachments.Add(att);

                    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
                    client.Send(mm);
                    this.Alert("Успешно изпращане");
                }
                catch (Exception ex)
                {
                    this.Alert(ex.Message + "\r\n" + ex.InnerException + "\r\n" + ex.StackTrace);
                }
            }
            else
            {
                this.Alert("Въведете поне един имейл адрес");
            }
        }

        protected void cvDamageDetails_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = Damage.DamageDetails.Count > 0;
        }

        protected void bCalcPercent_Click(object sender, EventArgs e)
        {
            EditSettings(1);
        }

        protected void bCalcSum_Click(object sender, EventArgs e)
        {
            EditSettings(2);
        }

        protected void rDamageDetails_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "EDIT":
                    DetailKindId = e.CommandArgument.ToString();
                    Edit();
                    break;
            }
        }

        protected void cvDamageDate_ServerValidate(object source, ServerValidateEventArgs args)
        {
            DateTime d;
            args.IsValid = DateTime.TryParse(args.Value, out d);
        }







        private void CancelDissasemblyTime()
        {
            mvCalc.SetActiveView(vTable);
        }


        protected void bCancelDissasemblyTime_Click(object sender, EventArgs e)
        {
            CancelDissasemblyTime();
        }

        protected void bDelPhoyto_Click(object sender, EventArgs e)
        {

        }

        private void ShowJustMinutes()
        {
            if (this.Damage.JustHours)
            {
                ddlSize1.SelectedValue = "0";
                ddlSize1.Visible = false;
                ddlSize2.SelectedValue = "0";
                ddlSize2.Visible = false;
                ddlSize3.SelectedValue = "0";
                ddlSize3.Visible = false;
                ddlSize4.SelectedValue = "0";
                ddlSize4.Visible = false;
                tbMinutes.Visible = true;
            }
            else
            {
                ddlSize1.Visible = true;
                ddlSize2.Visible = true;
                ddlSize3.Visible = true;
                ddlSize4.Visible = true;
                tbMinutes.Text = "0";
                tbMinutes.Visible = false;
            }
        }



        protected void tAutoSave_Tick(object sender, EventArgs e)
        {
            GetData();
            DB.Draft draft = dl.Drafts.FirstOrDefault(d => d.UserId == this.UserId);
            if (draft == null)
            {
                draft = new DB.Draft();
                dl.Drafts.InsertOnSubmit(draft);
            }
            draft.UserId = this.UserId.Value;
            draft.DraftXML = this.Damage.GetXml();
            dl.SubmitChanges();

        }

        protected void cvRegional_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = ucExpertisePlace.CityId != null;

        }

        private void GetDetailPrice()
        {
            if (mvCalc.ActiveViewIndex != 1)
                return;
            var detail = new Classes.DamageDetail()
            {
                DetailKindId = this.DetailKindId,
                Size1 = int.Parse(ddlSize1.SelectedValue),
                Size2 = int.Parse(ddlSize2.SelectedValue),
                Size3 = int.Parse(ddlSize3.SelectedValue),
                Size4 = int.Parse(ddlSize4.SelectedValue),
                Minutes = int.Parse(tbMinutes.Text == "" ? "0" : tbMinutes.Text),
                //JustHours = cbJustHours.Checked,
                DisassemblyTime = int.Parse(ddlDissasemblyTimeDetail.SelectedValue == "" ? "0" : ddlDissasemblyTimeDetail.SelectedValue),
                DisassemblyPrice = int.Parse(ddlDisassemblyPriceDetail.SelectedValue == "" ? "0" : ddlDisassemblyPriceDetail.SelectedValue),
                Materials = decimal.Parse(ddlAdditionalMaterials.SelectedValue),
                PNP = cbPNP.Checked,
                ALU = cbALU.Checked,
                Polish = cbPolish.Checked,
                Traditional = cbTraditional.Checked,
                WithReserve = cbWithReserve.Checked
            };
            int allAw = 0;
            bool isHorizontal = dl.DetailKinds.First(dk => dk.DetailKindId == this.DetailKindId).IsHorizontal;

            if (detail.Size1 > 0)
                allAw += this.Damage.CalcData.AWS.First(aw => aw.SizeTo == 1 && aw.IsHorizontal == isHorizontal && aw.Cnt == detail.Size1).AW;
            if (detail.Size2 > 0)
                allAw += this.Damage.CalcData.AWS.First(aw => aw.SizeTo == 2 && aw.IsHorizontal == isHorizontal && aw.Cnt == detail.Size2).AW;
            if (detail.Size3 > 0)
                allAw += this.Damage.CalcData.AWS.First(aw => aw.SizeTo == 3 && aw.IsHorizontal == isHorizontal && aw.Cnt == detail.Size3).AW;
            if (detail.Size4 > 0)
                allAw += this.Damage.CalcData.AWS.First(aw => aw.SizeTo == 4 && aw.IsHorizontal == isHorizontal && aw.Cnt == detail.Size4).AW;

            detail.AWS = allAw;
            detail.Obs = this.Obs;
            detail.ObsStr = this.GetObsString(detail.Obs);
            RecalcDetail(detail);
            lDetailPrice.Text = detail.Price.ToString("0.00");
        }

        protected void bRecalc_Click(object sender, EventArgs e)
        {
            GetDetailPrice();
        }

        protected void upRecalc_Load(object sender, EventArgs e)
        {
            if (ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)
                GetDetailPrice();
        }

        protected void bSaveDiscount2_Click(object sender, EventArgs e)
        {
            SaveSettings2();
        }

        protected void bCancelDiscount2_Click(object sender, EventArgs e)
        {
            mvCalc.SetActiveView(vTable);
        }

        protected void ddlAdditionalMaterialsTotal_SelectedIndexChanged(object sender, EventArgs e)
        {
            ReCalc();
        }

        private void UncolorDetail(ImageButton ib)
        {
            ib.BorderWidth = 0;
            ib.BorderColor = System.Drawing.Color.White;
        }
        private void ColorDetails()
        {
            UncolorDetail(bZLK);
            UncolorDetail(bZLV);
            UncolorDetail(bPLV);
            UncolorDetail(bPLK);
            UncolorDetail(bLK);
            UncolorDetail(bB);
            UncolorDetail(bKAS);
            UncolorDetail(bT);
            UncolorDetail(bK);
            UncolorDetail(bDK);
            UncolorDetail(bZDK);
            UncolorDetail(bZDV);
            UncolorDetail(bPDV);
            UncolorDetail(bPDK);

            ImageButton ib = null;
            foreach (var dd in Damage.DamageDetails)
            {
                switch (dd.DetailKindId)
                {
                    case "ZLK": ib = bZLK; break;
                    case "ZLV": ib = bZLV; break;
                    case "PLV": ib = bPLV; break;
                    case "PLK": ib = bPLK; break;
                    case "LK": ib = bLK; break;
                    case "B": ib = bB; break;
                    case "KAS": ib = bKAS; break;
                    case "T": ib = bT; break;
                    case "K": ib = bK; break;
                    case "DK": ib = bDK; break;
                    case "ZDK": ib = bZDK; break;
                    case "ZDV": ib = bZDV; break;
                    case "PDV": ib = bPDV; break;
                    case "PDK": ib = bPDK; break;
                }
                if (ib != null)
                {
                    ib.BorderWidth = 1;
                    ib.BorderColor = System.Drawing.Color.Red;
                }
            }

        }

        protected void ddlDissasemblyTime_SelectedIndexChanged(object sender, EventArgs e)
        {
            ReCalc();
        }

        protected void ddlPreparationTime_SelectedIndexChanged(object sender, EventArgs e)
        {
            ReCalc();
        }

        protected void bPhotos_Click(object sender, EventArgs e)
        {
            mvCalc.SetActiveView(vImages);
            ShowImages();
        }

        protected void bClose_Click(object sender, EventArgs e)
        {
            mvCalc.SetActiveView(vElement);
        }

        private void ShowImages()
        {
            var damageDetails = Damage.DamageDetails.Where(d => d.DetailKindId == this.DetailKindId).FirstOrDefault();
            if (damageDetails != null)
            {
                var photos = damageDetails.DetailPhotos;
                rPhotos.DataSource = photos;
                rPhotos.DataBind();
            }
            else
            {
                rPhotos.DataSource = null;
                rPhotos.DataBind();
            }


        }

        protected void bUploadPhoto_Click(object sender, EventArgs e)
        {
            if (fuPhoto.HasFile)
            {
                Guid guid = Guid.NewGuid();
                DB.Photo photo = new DB.Photo()
                {
                    IsDel = false,
                    LastEditDate = DateTime.Now,
                    Photo1 = new System.Data.Linq.Binary(fuPhoto.FileBytes),
                    PhotoId = guid
                };
                dl.Photos.InsertOnSubmit(photo);
                dl.SubmitChanges();
                var damageDetail = Damage.DamageDetails.Where(d => d.DetailKindId == this.DetailKindId).FirstOrDefault();
                if (damageDetail == null)
                {
                    damageDetail = new Classes.DamageDetail()
                {
                    DetailKindId = this.DetailKindId
                };
                    Damage.DamageDetails.Add(damageDetail);
                }
                damageDetail.DetailPhotos.Add(
                    new Classes.DetailPhoto()
                    {
                        PhotoId = guid
                    }
                    );
            }

            ShowImages();
        }

        private void DelPhoto(string photoId)
        {
            var photo = dl.Photos.First(p => p.PhotoId == Guid.Parse(photoId));
            photo.IsDel = true;
            photo.LastEditDate = DateTime.Now;
            dl.SubmitChanges();
            var photos = Damage.DamageDetails.Where(d => d.DetailKindId == this.DetailKindId).First().DetailPhotos;
            photos.Remove(photos.First(p => p.PhotoId == Guid.Parse(photoId)));
        }

        protected void rPhotos_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "DELPHOTO": DelPhoto(e.CommandArgument.ToString()); break;
            }
        }

        protected void ddlDisassemblyPrice_SelectedIndexChanged(object sender, EventArgs e)
        {
            ReCalc();
        }

        //Зареждане от ДБ
        //Запис в ДБ




    }
}